package mMap.hashDemo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.log4j.Logger;
import org.junit.Test;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Ajie
 * @date 2020-10-13
 * @function
 */
public class HashMap_Json {
    private static final Logger logger = Logger.getLogger(HashMap_Json.class);

    @Test
    public void testMap2Json(){
        HashMap<Object, Object> map = new HashMap<>();
        map.put("key1","v1");
        map.put("key2","v2");
        map.put("key3","v3");
        String s = new Gson().toJson(map);
        logger.info("testMap2Json: "+s);//  {"key1":"v1","key2":"v2","key3":"v3"}
        json2Map(s);
    }


    public void json2Map(String json){
        HashMap<String,String> map = new Gson().fromJson(json, new TypeToken<HashMap<String, String>>() {}.getType());

        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();

        while (iterator.hasNext()){
            Map.Entry<String, String> next = iterator.next();
            logger.info("json2Map: key:"+next.getKey()+" v:"+next.getValue());

        }

    }
}
